package cn.org.spring.wechar.controller;

import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.org.spring.common.util.StringUtil;
import cn.org.spring.wechar.bean.Result;
import cn.org.spring.wechar.entity.WeChatUser;
import cn.org.spring.wechar.prize.entity.RecTelPrize;
import cn.org.spring.wechar.prize.entity.RecTelPrizeRecord;
import cn.org.spring.wechar.prize.service.RecTelPrizeRecordService;
import cn.org.spring.wechar.prize.service.RecTelPrizeService;
import cn.org.spring.wechar.utils.CacheUtil;
import cn.org.spring.wechar.utils.PrizeRandomUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author： 谢辉
 * @date： 2021/5/18
 * @email: xieh_mail@163.com
 * @description： 抽奖
 * @modifiedBy：
 * @version: 1.0
 */
@Slf4j
@RestController
@RequestMapping("/v1/prize")
public class PrizeController {

    @Autowired
    RedisTemplate<Object, Object> redisTemplate;

    @Autowired
    CacheUtil cacheUtil;


    @Autowired
    RecTelPrizeService recTelPrizeService;

    @Autowired
    RecTelPrizeRecordService recTelPrizeRecordService;


    /**
     * 话费抽奖
     *
     * @return
     */
    @GetMapping("/getTelCharge")
    public Result getTelCharge(@RequestHeader(value = "wechat-token") String userId) throws Exception {
        // 校验
        if (StringUtils.isEmpty(userId)) {
            return Result.fail("获取用户信息失败");
        }

        // 查询话费优惠券奖品信息
        List<RecTelPrize> recTelPrizes = recTelPrizeService.selectAllByList();
        if (recTelPrizes == null) {
            return Result.fail("获取奖品信息失败，请稍后再试~");
        }
        Map<String, Integer> keyChanceMap = new HashMap<String, Integer>();
        for (RecTelPrize recTelPrize : recTelPrizes) {
            // key是话费优惠券的id，value是对应话费优惠券的中奖概率
            keyChanceMap.put(String.valueOf(recTelPrize.getId()), recTelPrize.getProbability());
        }


        // 抽奖
        Boolean exists = cacheUtil.exists("lottery:" + userId);
        if (exists) {
            return Result.fail("一天只能抽取一次，请您明天再来~~~");
        } else {
            // 返回的是中奖的话费优惠券信息id
            String result = PrizeRandomUtil.chanceSelect(keyChanceMap);
            if (StringUtil.isEmpty(result)) {
                result = "0";
            }
            long currentTime = System.currentTimeMillis();
            long diff = timeDiff(currentTime);
            if (diff > 0) {
                cacheUtil.set("lottery:" + userId, result + ":" + currentTime, diff, TimeUnit.MILLISECONDS);
            }

            RecTelPrizeRecord recTelPrizeRecord = new RecTelPrizeRecord();
            Object o = cacheUtil.get("wechatuser:" + userId);
            WeChatUser weChatUser = (WeChatUser) o;
            // 属性对拷，要求两个类的属性必须一致，才能对拷成功，不一致的属性需要手动拷贝
            BeanUtils.copyProperties(recTelPrizeRecord, weChatUser);
            log.info("属性对拷成功，内容是：【{}】", recTelPrizeRecord.toString());
            // 设置中奖id
            recTelPrizeRecord.setTelPrizeId(Integer.valueOf(result));
            // 设置抽奖时间
            recTelPrizeRecord.setDrawTime(new Date());
            // 未使用
            recTelPrizeRecord.setIsUse(0);
            // 奖品过期时间
            DateTime endDayTime = DateUtil.endOfDay(new Date());
            recTelPrizeRecord.setExpirationTime(parseTime(endDayTime.toString()));
            recTelPrizeRecordService.insert(recTelPrizeRecord);
            return Result.ok(result);
        }
    }


    /**
     * 获取当前时间和当天结束的时间差
     *
     * @param currentTimeMillis 单位毫秒
     * @return 时间差
     */
    private long timeDiff(long currentTimeMillis) {
        DateTime dateTime = DateUtil.endOfDay(new Date());
        long endDayOfMillis = dateTime.getTime();
        return (endDayOfMillis - currentTimeMillis);
    }


    /**
     * 根据时间字符串转换时间
     *
     * @param time
     * @return
     */
    private Date parseTime(String time) {
        try {
            DateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            return df.parse(time);
        } catch (ParseException e) {
            log.error("时间转换失败，时间格式要求是：yyyy-MM-dd HH:mm:ss，传入的格式是：【{}】", time);
        }
        return null;
    }
}
